package com.jwater.console.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/3/10
 * @version: 1.0
 */
@Component
public class WebSSHHandler implements WebSocketHandler {
    protected static Logger logger = LoggerFactory.getLogger(WebSSHHandler.class);
    @Autowired
    private WebSSHService webSSHService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info("用户:{},连接WebSSH", session.getAttributes().get("user_uuid"));
        //调用初始化连接
        webSSHService.initConnection(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        if (message instanceof TextMessage) {
            logger.info("用户:{},发送命令:{}", session.getAttributes().get("user_uuid"), message.toString());
            //调用service接收消息
            webSSHService.recvHandle(((TextMessage) message).getPayload(), session);
        } else if (message instanceof BinaryMessage) {

        } else if (message instanceof PongMessage) {

        } else {
            logger.error("Unexpected WebSocket message type: " + message);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        logger.error("数据传输错误");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        logger.info("用户:{}断开webssh连接", String.valueOf(session.getAttributes().get("user_uuid")));
        //调用service关闭连接
        webSSHService.close(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
